package com.cq.hd.system.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.system.excel.dto.HfMccExcelDto;
import com.cq.hd.system.excel.dto.HfRegionsExcelDto;
import com.cq.hd.system.po.TbHfMccPo;
import com.cq.hd.system.po.TbHfRegionsPo;
import com.cq.hd.system.service.TbHfMccService;
import com.cq.hd.system.service.TbHfRegionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class HfMccListener extends AnalysisEventListener<HfMccExcelDto> {

    private final TbHfMccService hfMccService;

    public HfMccListener(TbHfMccService hfMccService) {
        this.hfMccService = hfMccService;
    }

    @Override
    public void invoke(HfMccExcelDto hfMccExcelDto, AnalysisContext analysisContext) {
        save(hfMccExcelDto);
    }

    private void save(HfMccExcelDto hfMccExcelDto) {
        List<TbHfMccPo> list = hfMccService.list(new QueryWrapper<TbHfMccPo>()
                .eq("region_grade", 3)
                .eq("mcc_name", hfMccExcelDto.getHfmccName()));
        if (!CollectionUtils.isEmpty(list)) {
            return;
        }

        List<TbHfMccPo> provinces = hfMccService.list(new QueryWrapper<TbHfMccPo>()
                .eq("region_grade", 1)
                .eq("mcc_name", hfMccExcelDto.getHfmccOneName()));
        if (CollectionUtils.isEmpty(provinces)) {
            log.error("未找到省份数据");
            return;
        }

        TbHfMccPo tbProvinceHfRegionsPo = provinces.get(0);

        List<TbHfMccPo> citys = hfMccService.list(new QueryWrapper<TbHfMccPo>()
                .eq("parent_id", tbProvinceHfRegionsPo.getId())
                .eq("region_grade", 2)
                .eq("mcc_name", hfMccExcelDto.getHfmccTwoName()));
        if (CollectionUtils.isEmpty(citys)) {
            log.error("未找到省份数据");
            return;
        }

        TbHfMccPo tbCityHfRegionsPo = citys.get(0);

        TbHfMccPo tbHfMccPo = new TbHfMccPo();
        tbHfMccPo.setParentId(tbCityHfRegionsPo.getId());
        tbHfMccPo.setRegionGrade(3);
        tbHfMccPo.setMccName(hfMccExcelDto.getHfmccName());
        tbHfMccPo.setMccCode(hfMccExcelDto.getHfmccCode());
        hfMccService.save(tbHfMccPo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


}
